package org.ofbiz.autoconfig.auto;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javolution.util.FastMap;

public class AutoExportXmlServices {
    public static final String module = AutoExportXmlServices.class.getName();
    public static final String OFBIZ_HOME = System.getProperty("ofbiz.home");

    public static Map<String, Object> autoXmlExport(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	String ids = (String) context.get("ids");
	String xmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<entity-engine-xml>\n";
	try {
	    String[] idList = ids.split(",");
	    for (String id : idList) {
		GenericValue onlScFormHead = delegator.findOne("OnlScFormHead", UtilMisc.toMap("id", id), false);
		List<GenericValue> onlScFormFieldList = delegator.findByAnd("OnlScFormField",
			UtilMisc.toMap("cgformHeadId", id), UtilMisc.toList("orderNum"), false);

		GenericValue entity = removeUnavailableField(onlScFormHead);

		Iterator<Map.Entry<String, Object>> it = entity.entrySet().iterator();
		xmlContent += "  <OnlScFormHead ";
		while (it.hasNext()) {
		    Map.Entry<String, Object> entry = it.next();
		    String key = entry.getKey();
		    Object pkValue = entry.getValue();
		    if(UtilValidate.isNotEmpty(pkValue))xmlContent += " " + key + "=\"" + pkValue + "\"";
		}
		xmlContent += " />\n";

		for (GenericValue onlScFormField : onlScFormFieldList) {
		    GenericValue item = removeUnavailableField(onlScFormField);

		    Iterator<Map.Entry<String, Object>> it2 = item.entrySet().iterator();
		    xmlContent += "  <OnlScFormField ";
		    while (it2.hasNext()) {
			Map.Entry<String, Object> entry = it2.next();
			String key = entry.getKey();
			Object pkValue = entry.getValue();
			if(UtilValidate.isNotEmpty(pkValue))xmlContent += " " + key + "=\"" + pkValue + "\"";
		    }
		    xmlContent += " />\n";

		}
	    }

	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	xmlContent += "</entity-engine-xml>";
	result.put("nfs", xmlContent);
	return result;
    }

    public static Map<String, Object> exportOnlScFormXml(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	LocalDispatcher dispatcher = dctx.getDispatcher();
	Delegator delegator = dctx.getDelegator();
	Map<String, Object> serviceContext = FastMap.newInstance();
	String autoHeadId = (String) context.get("autoHeadId");

	try {

	    Debug.log("autoHeadId = " + autoHeadId);

	    GenericValue onlScFormHead = delegator.findOne("OnlScFormHead", UtilMisc.toMap("id", autoHeadId), false);

	    List<GenericValue> onlScFormFieldList = delegator.findByAnd("OnlScFormField",
		    UtilMisc.toMap("cgformHeadId", autoHeadId), UtilMisc.toList("orderNum"), false);

	    List list = new ArrayList();
	    list.add(removeUnavailableField(onlScFormHead));

	    for (GenericValue onlScFormField : onlScFormFieldList) {
		list.add(removeUnavailableField(onlScFormField));
	    }

	    Document doc = GenericEntity.makeXmlDocument(list);

	    result.put("doc", docToString(doc));
	    result.put("onlScFormHead", onlScFormHead);
	    result.put("onlScFormFieldList", onlScFormFieldList);
	    result.put("fieldSize", onlScFormFieldList.size());
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    private static String docToString(Document doc) {
	// XML转字符串
	String xmlStr = "";
	try {
	    TransformerFactory tf = TransformerFactory.newInstance();
	    Transformer t = tf.newTransformer();
	    t.setOutputProperty("encoding", "UTF-8");// 解决中文问题，试过用GBK不行
	    ByteArrayOutputStream bos = new ByteArrayOutputStream();
	    t.transform(new DOMSource(doc), new StreamResult(bos));
	    xmlStr = bos.toString();
	} catch (TransformerConfigurationException e) {
	    Debug.logError(e.getMessage(), module);
	} catch (TransformerException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return xmlStr;
    }

    @SuppressWarnings("unchecked")
    private static GenericValue removeUnavailableField(GenericValue gv) {

	GenericValue result = new GenericValue();

	List<String> list = new ArrayList();
	list.add("createdStamp");
	list.add("lastUpdatedStamp");
	list.add("createdTxStamp");
	list.add("lastUpdatedTxStamp");
	list.add("createBy");
	list.add("createTime");
	list.add("updateBy");
	list.add("updateTime");

	for (String key : list) {
	    if (gv.containsKey(key)) {
		gv.set(key, null);
	    }
	}

	result = gv;
	return result;

    }

    public static void main(String[] arg) throws InterruptedException, MalformedURLException, SAXException,
	    ParserConfigurationException, IOException {

	List list = new ArrayList();
//GenericValue gv = new GenericValue();
//
//gv.set("id", "1");
//gv.set("name", "name1");
//System.out.println(gv.toString());
//list.add(gv);
	String filePath = "D:\\workspace\\frame_sever\\applications\\hrm\\data\\xml/";
	String fileName = filePath + "HrAdjustSalary.txt";

	File file = new File(fileName);
	Document mainDoc = UtilXml.readXmlDocument(file.toURL());

	System.out.println(docToString(mainDoc));
//addToXmlDocument(nfsList,mainDoc);

	// UtilXml.writeXmlDocument(fileName, mainDoc);

    }

}
